package com.foreveross.push.socket;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import com.foreveross.chameleon.CheckInUtil;
import com.foreveross.zillasdk.ZillaDelegate;
import com.foss.ChameleonApplication;
/**
 * project:
 * author: wzq
 * date: 2014/7/21
 * description: 向socket服务器进行验证
 */
public class TokenValidator {
    private static int MAX_TIME_REGISTER_TO_SOCKET = 3;

    public interface OnRegResult {
        void handleRegResult(boolean isSucc, String value);
    }

    public void register(final String token, final OnRegResult regResult) {
        new Thread() {
            public void run() {
                registerInternal(token, regResult, 0);
            }
        }.start();
    }

    private void registerInternal(final String token, final OnRegResult regResult, final int currTryTime) {
        Context context = ChameleonApplication.getApplication();
        ZillaDelegate zillaDelegate = new ZillaDelegate() {
            @Override
            public void requestSuccess(final String result) {
                if(null != regResult) {
                    // 成功，进入主线程,回调
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {
                            regResult.handleRegResult(true, result);
                        }
                    };
                    new Handler(Looper.getMainLooper()).post(r);
                }
            }

            @Override
            public void requestStart() {
            }

            @Override
            public void requestFailed(final String errorMessage) {
                if(currTryTime > MAX_TIME_REGISTER_TO_SOCKET) {
                    if(null != regResult) {
                        Runnable r = new Runnable() {
                            @Override
                            public void run() {
                                regResult.handleRegResult(false, errorMessage);
                            }
                        };
                        new Handler(Looper.getMainLooper()).post(r);
                    }
                } else {
                    registerInternal(token, regResult, currTryTime + 1);
                }
            }
        };
        CheckInUtil.registerPush(context, token, zillaDelegate);
    }
}
